package com.yisu.expressway.login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.yisu.expressway.R;
import com.yisu.expressway.activity.BaseActivity;
import com.yisu.expressway.main_page.HomePageActivity;
import com.yisu.expressway.model.LoginEvent;
import com.yisu.expressway.model.UserProfile;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.utils.SocialUtils;
import com.yisu.expressway.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;

public class LoginPageActivity extends BaseActivity implements TextWatcher {

    @Bind(R.id.et_phone_number)
    protected EditText mEdt_phone;
    @Bind(R.id.action_next)
    protected Button mBtn_next;

    private InputMethodManager imm;
    private UMShareAPI umShareAPI;
    private boolean hasQQ;
    private boolean hasWeiXin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_page);
        EventBus.getDefault().register(this);
        init();
    }

    private void init(){
        setTitle(R.string.user_login);
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        umShareAPI = UMShareAPI.get(this);
        hasQQ = umShareAPI.isInstall(LoginPageActivity.this, SHARE_MEDIA.QQ);
        hasWeiXin = umShareAPI.isInstall(LoginPageActivity.this, SHARE_MEDIA.WEIXIN);

        mEdt_phone.addTextChangedListener(this);
        mEdt_phone.setFocusable(true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI umShareAPI = SocialUtils.getmShareAPI();
        if (umShareAPI != null) {
            umShareAPI.onActivityResult(requestCode, resultCode, data);
        }
    }


    @OnClick(R.id.action_next)
    public void getVerifyCode(){
        Map<String, Object> params = new HashMap();
        params.put("phoneNumber", mEdt_phone.getText().toString());

        ApiClientHelper.postApi(ApiSetting.getVerifyCode(), new TypeToken<Object>() {
        }, new JSONObject(params), new Response.Listener<ApiResult<Object>>() {
            @Override
            public void onResponse(ApiResult<Object> result) {
                if (!result.success) {
                    ToastUtil.displayLongToastMsg(LoginPageActivity.this, result.getMsg());
                    return;
                }

                ToastUtil.displayLongToastMsg(LoginPageActivity.this, R.string.verification_code_send_success);

                Intent i = new Intent(LoginPageActivity.this, VerificationCodeLoginActivity.class);
                i.putExtra(VerificationCodeLoginActivity.INTENT_KEY_PHONE_NUMBER, mEdt_phone.getText().toString());
                startActivity(i);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastUtil.displayShortToastMsg(LoginPageActivity.this, volleyError.getMessage());
            }
        }, this);
    }

    @OnClick({R.id.btn_wx,R.id.btn_sina,R.id.btn_qq})
    public void doThirdPartyLoginClick(ImageButton button){
        int type = -1;
        switch (button.getId()) {
            case R.id.btn_sina:
                type = UserProfile.LOGIN_TYPE_WEIBO;
                break;
            case R.id.btn_wx:
                if (hasWeiXin) {
                    type = UserProfile.LOGIN_TYPE_WEIXIN;
                } else {
                    ToastUtil.displayShortToastMsg(LoginPageActivity.this, R.string.login_no_weixin);
                }
                break;
            case R.id.btn_qq:
                if (hasQQ) {
                    type = UserProfile.LOGIN_TYPE_QQ;
                } else {
                    ToastUtil.displayShortToastMsg(LoginPageActivity.this, R.string.login_no_qq);
                }
                break;
            default:
                break;
        }
        if (type != -1) {
            SocialUtils.authLogin(LoginPageActivity.this, type);
        }

    }

    @Subscribe
    public void onReceiverLoginEvent(LoginEvent event){
        if(event.getLoginResult()){
            finish();
        }
    }

    /**
     * 调起登录页，同时关闭最顶层Activity，为账号登录其他设备用
     * @param context 最顶层Activity
     */
    public static void launch(Activity context){
        Intent intent = new Intent(context,LoginPageActivity.class);
        context.startActivity(intent);
        if(context.getClass() != HomePageActivity.class) {
            context.finish();
        }

    }


    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (11 == s.length()){
            mBtn_next.setEnabled(true);
        }else{
            mBtn_next.setEnabled(false);
        }
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
        ApiClientHelper.dequeue(this);
        EventBus.getDefault().unregister(this);
    }


    @Override
    public void onBackPressed() {
        EventBus.getDefault().post(new LoginEvent(false));
        super.onBackPressed();
    }
}
